class ShopsController < ApplicationController
 layout "background",:except=>[:index,:show_products]
 before_filter:authorize,
              :except=>[:index,:new,:show_products]
 before_filter:has_shop,
                :except=>[:index,:new,:show_products]

  
  def authorize
    unless User.find_by_id(session[:user_id])
      notice("请先登录！")
      session[:last_uri]=request.request_uri
      redirect_to_login
    end
  end
  def has_shop
      @shop=Shop.find_by_user_id(session[:user_id])
      unless @shop
        notice("你还没有开通商铺！请先开通商铺")
        redirect_to(:action=>:new)
      end
  end
  # GET /shops
  # GET /shops.xml
  def index   
    @shops = Shop.paginate(:all,:include=>[:user],:page=>params[:page]||1,:per_page=>5)
    render(:layout=>"layouts/common")
  end
  
  def show_products
    @products=Product.paginate(:all,:conditions=>["shop_id= ? ",params[:id]],:page => params[:page]||1,:per_page => 5)
    render(:layout=>"layouts/common")
  end

  # GET /shops/new
  # GET /shops/new.xml
  def new
  end

  def edit
  end
  
  def create
      @shop=Shop.new(params[:shop])
      @shop.user_id=session[:user_id]
      @shop.status="open"
      begin
        @shop.save!
      rescue ActiveRecord::RecordNotSaved
        redirect_to_error_msg("开通商铺失败！")
      else
        notice("开通商铺成功！")
        redirect_to(:action=>:shop_show)
      end   
  end
  
  def show
  end
  
  # Post manage_shop/shop_update
  def update
      begin
        @shop.update_attributes!(params[:shop])
      rescue ActiveRecord::RecordNotSaved
        redirect_to_error_msg("商铺信息更新失败！")        
      else
        notice("商铺信息更新成功！")
        redirect_to(:action=>:show)
      end
    end
end
